package smashedapples.google.datastore
{
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	import smashedapples.core.NonVisualComponent;
	import smashedapples.utils.ArrayUtils;
	import smashedapples.utils.StructUtils;
	
	
	
	
	
	public class Query extends NonVisualComponent
	{	
		[Transient]
		[Bindable] public var result:Struct;
	
		public var modelName:String;
		
		public var datastore:DataStore;
		
		[Inspectable( enumeration="true,false",defaultValue="true")]
		public var updateOnSave:Boolean = true;
		
		[Inspectable( enumeration="true,false",defaultValue="true")]
		public var updateOnDelete:Boolean = true;
		
		public var maxrows:Number = 1000;
		
		public var parameters:Object = {};
		
		public var order:String;
		
		private var _gql:String;
		
		public function get gql():String
		{
			return _gql;
		}
		
		public function set gql( value:String ):void
		{
			_gql = value;
		}
		
		
		public function resultHandler( event:ResultEvent ):void
		{
			
			Debug.push( this, event.result );

			if( event.result is Array)
				this.result = StructUtils.createByKey( event.result as Array, "_key" );
		}
		
		
		
		
		public function send( data:*=null, result:Function=null, fault:Function = null ):AsyncToken
		{
			this.setQuery( data );	
			return this.datastore.select( this );
		}
		
		
		public function faultHandler( event:FaultEvent ):void
		{
			Debug.push( this, event.fault );
		}
		
		
		public function setQuery( data:* = null ):void
		{
			if( data == null )
				return;
			 
			for ( var key:String in data )
            {	
            	if( this.hasOwnProperty( key ) )
            	{
            		this[ key ] = data[ key ];
            	}
            	else
            	{
            		parameters
            	}
	       		
            }
		}
		
		
		public function updateDeletedItems( keys:Array = null ):void
		{	
			if( keys == null )
				return;
			
			if( !this.updateOnDelete )
				return;
			
			
			for each( var key:String in keys)
			{
				var index : int = ArrayUtils.getIndexByID( result.source, "_key", key); 
				if( index != -1 )
					this.result.removeItemAt( index );
			}
		}
		
		public function updateSavedItem( item:Object ):void
		{

			if( !this.updateOnSave )
				return;
				
			//var index : int = ArrayUtils.getIndexByID( result.source, "_key",item["_key"]);
			
			/* Debug.push( this, item );
			
			if ( index == -1)
			{
				result.addItem( item );
			}
			else
			{
				result.setItemAt( item, index );	
			} */
		}
		
		
	}
}